import { authMiddleware } from '@/lib/api';
import { clientQueryUserDetails, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import ResetPage from '@/app/[locale]/reset/reset';
import { Metadata as MetadataNext } from 'next';
import { IPath } from '@/interfaces';
import { getMetadata } from '@/lib/tool';
import { notFound } from 'next/navigation';
import HomeUserIdH5Page from '@/app/[locale]/mobile/users/home/h5';

export async function generateMetadata({
  params,
  searchParams,
}: {
  params: {};
  searchParams?: {};
}): Promise<MetadataNext> {
  try {
    const token = authMiddleware(cookies());
    const resp1 = await (
      (await queryPath({
        baseURL: process.env.APP_API_SERVER,
        token,
        query: {
          name: '/',
        },
      })) as Response
    ).json();
    const data = resp1.data as IPath;

    if (data.user) {
      return getMetadata({
        title: data.user.alias,
        authors: {
          url: `/${data.user.id}`,
          name: data.user.alias,
        },
        creator: `${data.user.alias}(${data.user.id})`,
        description: `${data.user.alias} - 个人主页`,
      });
    } else {
      return getMetadata({
        title: '无名大侠',
        description: `无名大侠 - 个人主页`,
      });
    }
  } catch (e) {
    return getMetadata({ title: '用户主页' });
  }
}

export default async function Page({
  params = {},
  searchParams = {},
}: {
  params: {};
  searchParams: {
    v?: 'h5';
  };
}) {
  if (searchParams.v !== 'h5') {
    notFound();
  }

  try {
    const metadata = new Metadata();
    const token = authMiddleware(cookies());
    const resp1 = await (
      (await queryPath({
        baseURL: process.env.APP_API_SERVER,
        token,
        query: {
          name: '/',
        },
      })) as Response
    ).json();
    const data = resp1.data as IPath;

    if (data.user) {
      const id = data.user.id;
      const req2 = clientQueryUserDetails({
        baseURL: process.env.APP_API_SERVER,
        token,
        id,
        query: searchParams,
      });

      const responses = await Promise.all([req2]);
      const resp2 = await ((await responses[0]) as Response).json();
      metadata.set(
        'userId',
        ['/users', '/client', id, '/details', searchParams, 'infinite'],
        resp2.data,
      );
    }

    metadata.set('page', ['/paths', '/'], data);
    return <HomeUserIdH5Page metadata={metadata.toString()} />;
  } catch (e) {
    return <ResetPage error={e} />;
  }
}
